import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-03-21
 * Time: 14:51
 */
public class JDBCSearchDemo {
    public static void main(String[] args) throws SQLException {
        // 1. 创建数据源
        DataSource dataSource = new MysqlDataSource();
        // ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java0321?characterEncoding=utf8&SSL=false");
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java0321?characterEncoding=utf8&useSSL=false");

        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("lyf2021");

        // 2. 建立连接
        Connection connection = dataSource.getConnection();

        // 3. 构建 sql 语句
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);

        // 4. 执行 sql 语句
        ResultSet resultSet = statement.executeQuery();
        while(resultSet.next()) {
            // 获取对应的 表中的列名
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println(id+ " : " + name);
        }

        // 5. 释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
